package org.example.springmybatisdemo.controller;

import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.BucketAuthorization;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileBucketLocalAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.BucketResponse;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.HttpClient;
import cn.ucloud.ufile.http.OnProgressListener;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.springmybatisdemo.entity.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

//@Api(tags = "文件上传接口")
@RestController
@Tag(name = "文件上传", description = "文件上传相关接口")
@Slf4j
public class UploadController {
//    本地存储
//    @ApiOperation("文件上传到本地")
    @PostMapping("/uploadlocal")
    @Operation(summary = "本地文件上传", description = "将文件上传到本地服务器")
    public Result<String> uploadlocal(MultipartFile file) throws IOException {

        log.info("文件上传开始");
        // 添加空值检查
        if (file == null || file.isEmpty()) {
            return Result.fail("文件不能为空", 400);
        }
//        获取原始文件名
        String originalFilename = file.getOriginalFilename();

//        通过uuid创建随机字符串
        String uuid = java.util.UUID.randomUUID().toString();

        originalFilename.substring(originalFilename.lastIndexOf("."));

        file.transferTo(new File("D:/" + uuid + originalFilename));

        return Result.success("上传成功");
    }

//    @ApiOperation("文件上传到UCloud")
    @PostMapping("/upload")
    @Operation(summary = "UCloud文件上传", description = "将文件上传到UCloud对象存储")
    public  Result<String> upload(MultipartFile file) throws IOException {
//        配置UfileClient，必须在使用UfileClient之前调用
        UfileClient.configure(new UfileClient.Config(
                new HttpClient.Config(10, 5, TimeUnit.MINUTES)
                        .setTimeout(10 * 1000, 30 * 1000, 30 * 1000)
                        .setExecutorService(Executors.newSingleThreadExecutor())));

        // Bucket相关API的授权器
        BucketAuthorization BUCKET_AUTHORIZER = new UfileBucketLocalAuthorization(
                "4eZCZdbpU4mLSVRNyBUWhNDbROuOYHUP0", "LdmF6ZixJTaLp7tuvNkxtLGU8lm2grHRz9whakCaBZoV");

//        UfileClient.bucket(BUCKET_AUTHORIZER)
//                .APIs       // Bucket相关操作API
//                .execute() or executeAsync(UfileCallback<T>)
//        try {
////            bucketName:上传域名的前缀
////            地域region https://docs.ucloud.cn/api/summary/regionlist
//            BucketResponse res = UfileClient.bucket(BUCKET_AUTHORIZER)
//                    .createBucket("xiangzizhuye", "cn-gd", bucketType)
//                    .execute();
//        } catch (UfileClientException e) {
//            e.printStackTrace();
//        } catch (UfileServerException e) {
//            e.printStackTrace();
//        }


//        上传
//        File file = new File("your file path");  //filepath
        File tempFile = null;
//        PublicKey:  https://console.ucloud.cn/uapi/apikey 获取
        try {
            ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
                    "4eZCZdbpU4mLSVRNyBUWhNDbROuOYHUP0", "LdmF6ZixJTaLp7tuvNkxtLGU8lm2grHRz9whakCaBZoV");

            // 创建临时文件
            tempFile = File.createTempFile("upload_", "_" + file.getOriginalFilename());
            // 将MultipartFile内容写入临时文件
            file.transferTo(tempFile);

//            ObjectConfig("your bucket region", "ufileos.com")
//            1) bucket region: https://docs.ucloud.cn/api/summary/regionlist
//            2) bucketType: All：用户所有可见的仓库， User：用户个人创建的仓库 ， Share：第三方公开镜像， 默认值：All
            ObjectConfig config = new ObjectConfig("cn-gd", "ufileos.com");
            PutObjectResultBean response = UfileClient.object(OBJECT_AUTHORIZER, config)
                    .putObject(tempFile, file.getContentType())
                    .nameAs(file.getOriginalFilename())           //key
                    .toBucket("xiangzizhuye")  //bucket
                    /**
                     * 是否上传校验MD5, Default = true
                     */
                    //  .withVerifyMd5(false)
                    /**
                     * 指定progress callback的间隔, Default = 每秒回调
                     */
                    //  .withProgressConfig(ProgressConfig.callbackWithPercent(10))
                    /**
                     * 配置进度监听
                     */
                    .setOnProgressListener(new OnProgressListener() {
                        @Override
                        public void onProgress(long bytesWritten, long contentLength) {

                        }
                    })
                    .execute();
            if (response != null && response.getRetCode() == 0) {
                int expiresDuration = 5 * 60; //  5 * 60秒 --> 5分钟后过期
                String url = UfileClient.object(OBJECT_AUTHORIZER, config)
                        .getDownloadUrlFromPrivateBucket(file.getOriginalFilename(), "xiangzizhuye", expiresDuration)
                        .createUrl();
                System.out.println("地址："+url);

            } else {
//                log.error("upload error,{}", response);
                System.out.println(response);
                throw new RuntimeException("File Upload Error");
            }
        } catch (UfileClientException e) {
            e.printStackTrace();
        } catch (UfileServerException e) {
            e.printStackTrace();
        }

        return Result.success("上传成功");
    }
}
